#!/bin/sh

file=$1

if [ $# = 0 ] ; then
    echo >&2 "usage: `basename "$0"` <file>"
    exit 1
fi

if [ ! -r "$file" ] ; then
  echo >&2 "Unable to read file '$file'." 
  exit 1
fi

url=https://www.virustotal.com/search.html

# Hash.
hash=`sha256sum "$file" | cut -d' ' -f1`

# Upload.
echo >&2 "Uploading file '$file' with hash '$hash' for analysis."
data=`curl --silent --show-error --max-redirs 1000 -L "$url" -d "chain=$hash"`

# Handle unknown file.
if echo "$data" | grep -q 'File not found' ; then
  echo "File '$file' is unknown to VirusTotal."
  exit
fi

# Extract rate.
rate=`echo "$data" | grep '[0-9]\+ out of [0-9]\+ antivirus' |
      sed 's/^\s*\([0-9]\+\)[^0-9]\+\([0-9]\+\).*/\1 of \2/'`

if [ $? != 0 ] ; then
    echo >&2 "A network error occured while attempting to upload '$file' for analysis."
    exit 1
fi

case "$rate" in
  0\ of*)
    echo "File '$file' is clean according to VirusTotal."
    ;;
  '')
    echo >&2 "Unable to determine detection rate for file '$file'."
    exit 1
    ;;
  *)
    echo "File '$file' is malware. VirusTotal detection rate: $rate."
    ;;
esac

# vim: set ts=2 et:
